<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.cardNum"
        placeholder="请输入油卡卡号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-date-picker
        v-model="listQuery.startDay"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="选择开始日期时间"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-date-picker
        v-model="listQuery.endDay"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        placeholder="选择结束日期时间"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <!-- <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate(2)"
      >
        新增主卡
      </el-button> -->
    </div>

    <el-table
      :key="key"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        label="序号"
        prop="id"
        align="center"
        width="50"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="supplyCompany"
        label="商户名称"
        align="center"
        width=""
      />
      <el-table-column
        prop="supplyPhone"
        label="联系电话"
        align="center"
        width=""
      />
      <el-table-column
        prop="cardNum"
        label="主卡号"
        align="center"
        width=""
      />
      <el-table-column
        label="类型"
        width=""
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.sourceId | typeFilter1 }}
        </template>
      </el-table-column>

      <el-table-column
        label="卡面金额"
        min-width=""
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.money }}
        </template>
      </el-table-column>

      <el-table-column
        prop="currentMoney"
        label="库存金额"
        align="center"
        width=""
      />

      <el-table-column
        prop="payMoney"
        label="应付金额"
        align="center"
        width=""
      />

      <el-table-column
        label="是否高挂卡"
        width=""
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.isHang | typeFilter }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="260px"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            style="width: 75px;"
            @click="unBind(scope.row)"
          >充值
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="2vh"
      width="680px"
    >
      <el-form
        ref="temp"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
        style="width:550px; margin-left:50px;"
      >
        <el-form-item
          label="主卡名称"
          prop="name"
        >
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item
          label="主卡卡号"
          prop="cardNum"
        >
          <el-input v-model="temp.cardNum"/>
        </el-form-item>

        <el-form-item
          label="主卡来源"
          prop="source"
        >
          <el-input v-model="temp.source"/>
        </el-form-item>

        <el-form-item
          v-permission="['admin']"
          label="所属省代"
          prop="agentId"
        >
          <el-select
            @change="selectAgentSearchSupply"
            v-model="temp.agentId"
            class="filter-item"
          >
            <el-option
              v-for="item in allAgent"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="所属商户"
          prop="supplyId"
        >
          <el-select
            v-model="temp.supplyId"
            class="filter-item"
          >
            <el-option
              v-for="item in allSupply"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="createData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>

    </el-dialog>

    <el-dialog
      title="充值"
      :visible.sync="dialogFormVisibleRech"
      top="2vh"
      width="680px"
    >
      <el-form
        ref="tempRech"
        :rules="rulesRech"
        :model="tempRech"
        label-position="left"
        label-width="110px"
        style="width:550px; margin-left:50px;"
      >
        <el-form-item
          label="主卡名称"
          prop="name"
        >
          <el-input
            :disabled="true"
            v-model="tempRech.name"
          />
        </el-form-item>
        <el-form-item
          label="主卡卡号"
          prop="cardNum"
        >
          <el-input
            v-model="tempRech.cardNum"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item
          label="卡面金额"
          prop="money"
        >
          <el-input v-model="tempRech.money"/>
        </el-form-item>

        <el-form-item
          label="应付金额"
          prop="buyMoney"
        >
          <el-input v-model="tempRech.buyMoney"/>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisibleRech = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="createDataRech()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
  import permission from "@/directive/permission/index.js"; // 权限判断指令
  import checkPermission from "@/utils/permission"; // 权限判断函数

  import {
    getOilSupplyList,
    createOilSupply,
    getallAgent,
    getOilCardPage,
    addOrUpdateOilCard,
    getSupplyAll,
    masterCardRech,
    getMainCardList,
    highCardRech,
  } from "@/api/v1";
  import {supplyUnBind} from "@/api/user";

  import waves from "@/directive/waves"; // Waves directive
  import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
  import {parseTime} from "@/utils";
  import addImgall from "@/components/img";
  import provinceData from "@/components/province";

  export default {
    directives: {waves, permission},
    components: {Pagination, addImgall, provinceData},
    filters: {
      typeFilter(role) {    //是否高挂 1是   2否
        switch (role) {
          case 1:
            return "是";
          case 2:
            return "否";
        }
      },
      typeFilter1(role) {    //是否高挂 1加油   2加气
        switch (role) {
          case 1:
            return "中石油";
          case 2:
            return "中石化";
        }
      },
    },
    data() {
      return {
        editPhone: true,
        imageUrl: "",
        tableData: [],
        allAgent: [],
        allSupply: [],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        cooperation: [],
        listQuery: {
          cardNum: null,
          page: 1,
          limit: 20,
          sort: "+id",
          type: 1,
          startDay: "",
          endDay: ""
        },
        key: 1, // table key
        dialogFormVisible: false,
        dialogFormVisibleRech: false,
        rules: {
          name: [{required: true, message: "请输入名称", trigger: "blur"}],
          agentId: [
            {required: true, message: "请选择所属省代", trigger: "change"}
          ],
          supplyId: [
            {required: true, message: "请选择商户", trigger: "change"}
          ],
          cardNum: [{required: true, message: "请输入卡号", trigger: "blur"}],
          source: [{required: true, message: "请输入来源", trigger: "blur"}]
        },
        rulesRech: {
          money: [{required: true, message: "请输入充值金额", trigger: "blur"}],
          buyMoney: [
            {required: true, message: "请输入购买金额", trigger: "blur"}
          ]
        },
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "新增"
        },
        temp: {
          id: null,
          name: "",
          cardNum: "",
          agentId: "",
          supplyId: "",
          type: 1,
          state: 0
        },
        tempRech: {
          cardId: null,
          name: null,
          carcNum: null,
          money: null,
          buyMoney: null
        },
        isAdmin: true
      };
    },
    watch: {
      checkboxVal(valArr) {
        this.formThead = this.formTheadOptions.filter(
          i => valArr.indexOf(i) >= 0
        );
        this.key = this.key + 1; // 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
      }
    },

    created() {
      const id = this.$route.query.id;
      this.listQuery.cooperation = id;
      this.getList();
      if (checkPermission(["admin"])) {
        this.getList2();
      } else {
        this.isAdmin = false;
//      getSupplyAll().then(res => {
//        this.allSupply = res.data;
//      });
      }
    },
    methods: {
      selectAgentSearchSupply(id) {
        this.listLoading = true;
        getSupplyAll({agentId: id}).then(res => {
          this.allSupply = res.data;
          this.temp.supplyId = null;
        });
        this.listLoading = false;
      },
      detail(row) {
        console.log(row);
        this.$router.push({
          path: "/subCard",
          query: {
            parentId: row.id,
            cardNum: row.cardNum,
            agentId: row.agentId,
            name: row.name,
            source: row.source
          }
        });
      },
      resetTemp() {
        this.temp = {
          name: "",
          cardNum: "",
          agentId: "",
          supplyId: "",
          type: 1,
          state: 0
        };
      },
      resetTempRech() {
        this.tempRech = {
          cardId: null,
          name: null,
          carcNum: null,
          money: null,
          buyMoney: null
        };
      },
      handleCreate(role) {
        this.resetTemp();
        this.temp.role = role;
        console.log(this.temp);
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
        this.editPhone = false;
        this.$nextTick(() => {
          this.$refs["temp"].clearValidate();
        });
      },
      unBind(row) {
        this.resetTempRech();
        this.dialogFormVisibleRech = true;
        this.tempRech.cardId = row.id;
        this.tempRech.name = row.name;
        this.tempRech.cardNum = row.cardNum;
      },
      createDataRech() {
        this.$refs["tempRech"].validate(valid => {
          if (valid) {
            masterCardRech(this.tempRech).then(res => {
              this.dialogFormVisibleRech = false;
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
              this.getList();
            });
          }
        });
      },
      createData() {
        if (!checkPermission(["admin"])) {
          this.temp.agentId = 0;
        }
        this.$refs["temp"].validate(valid => {
          if (valid) {
            highCardRech(this.temp).then(res => {
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
              this.getList();
            });
          }
        });
      },
      handleUpdate(row) {
        getSupplyAll({agentId: row.agentId}).then(res => {
          this.allSupply = res.data;
          this.temp = Object.assign({}, row); // copy obj
          this.dialogStatus = "update";
          this.dialogFormVisible = true;
          this.editPhone = true;
          this.$nextTick(() => {
            this.$refs["temp"].clearValidate();
          });
        });
      },
      getList() {
        this.listLoading = true;
        getMainCardList(this.listQuery).then(res => {
          this.tableData = res.data.records;
          this.total = Number(res.data.total);
          console.log(this.tableData);
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },
      getList2() {
        this.listLoading = true;
        getallAgent(this.listQuery).then(res => {
          this.allAgent = res.data;
        });
        this.listLoading = false;
      },
      getCooperationAll() {
        cooperationAll().then(res => {
          this.cooperation = res.data;

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      }
    }
  };
</script>

